
#include "dk_core.h"
#include "ds_conf.h"
#include "server.h"
#include "logger.h"
#include "storage.h"

int main(int argc, char **argv) {
  if (!g_conf || !g_conf->Init("./ds.conf")) {
    fprintf(stderr, "config init error\n");
    return 1;
  }

  if (!g_logger ||
      !g_logger->Init(g_conf->log_file.c_str(),
                      4, true,
                      g_conf->rotate_megabytes*1024*1024)) {
    fprintf(stderr, "logger init error\n");
    return 1;
  }

  if (!g_storage || !g_storage->Init()) {
    fprintf(stderr, "storage init fail\n");
    return 1;
  }

  if (!g_work_thread_pool ||
      !g_work_thread_pool->Init(g_conf->threads)) {
    fprintf(stderr, "work thread pool init fail\n");
    return 1;
  }


  if (!g_server || !g_server->Init()) {
    fprintf(stderr, "server Init error\n");
    return 1;
  }
  
  LOG_INFO("server start ......");

  signal(SIGPIPE, SIG_IGN);
  signal(SIGHUP, SIG_IGN);

  int port = 8080;
  if (argc > 1) {
    port = atoi(argv[1]);
  }

  if (!g_server->StartListenTCP(NULL, g_conf->listen_port, 1024)) {
    LOG_ERROR("StartListenTCP fail (:%d)", port);
    return 1;
  }

  g_server->set_timeout(g_conf->client_timeout);
  g_server->EventLoop();

  return 0;
}
